﻿namespace CatClient.Message.Spi.Heartbeat.Extend
{
    using CatClient.Util;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    public class DiskIO : HeartbeatExtention, IDisposable
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly Dictionary<string, double> _dict;
        private readonly PerformanceCounter _readBytesSec;
        private readonly PerformanceCounter _writeByteSec;
        private readonly PerformanceCounter _dataBytesSec;

        public DiskIO()
        {
            this._stopwatch.Start();
            this._dict = new Dictionary<string, double>();
            this._readBytesSec = new PerformanceCounter("PhysicalDisk", "Disk Reads/sec", "_Total");
            this._writeByteSec = new PerformanceCounter("PhysicalDisk", "Disk Writes/sec", "_Total");
            this._dataBytesSec = new PerformanceCounter("PhysicalDisk", "Disk Transfers/sec", "_Total");
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"DiskIO"} init finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public void Dispose()
        {
            if (this._readBytesSec != null)
            {
                this._readBytesSec.Dispose();
            }
            if (this._writeByteSec != null)
            {
                this._writeByteSec.Dispose();
            }
            if (this._dataBytesSec != null)
            {
                this._dataBytesSec.Dispose();
            }
            GC.SuppressFinalize(this);
        }

        public override void Refresh()
        {
            this._stopwatch.Restart();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info("Heartbeat DiskIO Refresh.");
            this._dict["Read"] = this._readBytesSec.NextValue();
            this._dict["Write"] = this._writeByteSec.NextValue();
            this._dict["Total"] = this._dataBytesSec.NextValue();
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"CpuInfo"} refresh finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public override Dictionary<string, double> Dict =>
            this._dict;

        public override string Id =>
            "DiskIO";
    }
}

